import {
  getRecommendList,
  getCategoryList,
  getSubList,
  getShopCarList,
  shopCarAdd
} from "../../utils/config";
import store from "../../utils/factory";

let that = null;
//获取应用实例
const app = getApp();

Component({
  pageLifetimes: {
    show() {
      if (typeof this.getTabBar === "function" && this.getTabBar()) {
        this.getTabBar().setData({
          selected: 1
        });
        this.getTabBar().setData({
          count: 0
        });
        if (store.get("userInfo")) {
          this.getTotal();
        }
        if (store.get("pageSource")) {
          store.remove("pageSource");
          return false;
        }
        this.getCategoryList();
      }
    }
  },
  data: {
    goodsH: 0,
    leftGoodsH: 0,
    animation: true,
    catHighLightIndex: 99,
    currentName: "",
    categoryPage: 1,
    categoryLimit: 20,
    largeclassList: [],
    subList: [],
    topList: [],
    currentSubId: null,
    subPage: 1,
    subLimit: 10,
    topIndex: 0,
    topListW: 300,
    toView: ""
  }, // 私有数据，可用于模板渲染
  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached: function () {
    that = this;
    let systemInfo = store.get("systemInfo");
    console.log(systemInfo);
    if (!systemInfo) {
      this.settingModel();
      return false;
    }
    let tabBarHeight = 50;
    if (systemInfo.model.search("iPhone X") != -1) {
      tabBarHeight = 34 + 50;
    }
    this.setData({
      goodsH: systemInfo.windowHeight - 52 - tabBarHeight,
      leftGoodsH: systemInfo.windowHeight - 52 - tabBarHeight,
      topListW: systemInfo.windowWidth - 100,
      catHighLightIndex: 0,
      topList: []
    });
    // this.getRecommendList("每日推荐");
  }, // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready: function () {},
  methods: {
    goSearch() {
      wx.navigateTo({
        url: `../search/search`
      });
    },
    onShareAppMessage() {
      return {
        title: "热度零食铺",
        path: '/pages/index/index'
      }
    },
    settingModel() {
      wx.getSystemInfo({
        //  获取页面的有关信息
        success: function (res) {
          store.set("systemInfo", res);
          let model = res.model;
          let tabBarHeight = 50;
          if (model.search("iPhone X") != -1) {
            store.set("iphoneX", "in");
            tabBarHeight = 34 + 50;
          } else {
            store.set("iphoneX", "out");
          }
          that.setData({
            goodsH: res.windowHeight - 52 - tabBarHeight,
            leftGoodsH: res.windowHeight - 52 - tabBarHeight,
            topListW: res.windowWidth - 100
          });
        }
      });
    },
    getTotal() {
      getShopCarList().then(res => {
        let req = res.data;
        this.getTabBar().setData({
          count: req.quantity || 0
        });
      });
    },
    getRecommendList(name) {
      getRecommendList({
        type: 2,
        page: 1,
        limit: 99,
        name: name
      }).then(res => {
        let req = res.data
        req.map(item => {
          item.progress = parseInt(item.nowQuantity / item.minQuantity * 100);
          if (item.progress > 100 || item.progress == 100) {
            item.progress = 100
          }
        })
        that.setData({
          subList: req
        });
        console.log("请求每日推荐");
        wx.hideLoading();
      });
    },
    addShopCar: function (e) {
      if (!store.get("userInfo")) {
        wx.navigateTo({
          url: "../autoLogin/autoLogin" // 页面 B
        });
        return false;
      }
      console.log(e);
      let detailObj = e.currentTarget.dataset.obj;
      let index = e.currentTarget.dataset.index;
      let subList = this.data.subList;
      if (!detailObj) {
        wx.showToast({
          title: "该商品不存在",
          icon: "none"
        });
        return false;
      }
      if (detailObj.saleOut) {
        wx.showToast({
          title: "该商品已经售罄",
          icon: "none"
        });
        return false;
      }
      subList[index].shoppingCartNumber = subList[index].shoppingCartNumber + 1;
      shopCarAdd({
        category: detailObj.id,
        quantity: 1
      }).then(res => {
        wx.showToast({
          title: "添加购物车成功",
          icon: "none",
          duration: 1000
        });
        this.setData({
          subList: subList
        });
        this.getTabBar().setData({
          count: parseInt(this.getTabBar().data.count) + 1
        });
      });
    },
    goDetail(e) {
      const id = e.currentTarget.dataset.id;
      console.log(id);
      store.set("pageSource", "classify");
      wx.navigateTo({
        url: `../logs/logs?id=${id}`
      });
    },
    getSubList() {
      getSubList({
          page: this.data.subPage,
          limit: 10,
          id: this.data.currentSubId
        })
        .then(res => {
          if (res.rows.length > 0 || res.rows.length == 0) {
            let req = res.rows
            req.map(item => {
              item.progress = parseInt(item.nowQuantity / item.minQuantity * 100);
              if (item.progress > 100 || item.progress == 100) {
                item.progress = 100
              }
            })
            that.setData({
              subList: req
            });
            wx.hideLoading();
          }
        })
        .catch(err => {
          wx.hideLoading();
        });
    },
    getCategoryList() {
      getCategoryList({
        page: this.data.categoryPage,
        limit: this.data.categoryLimit,
        name: ""
      }).then(res => {
        let req = res.data;
        if (req.length > 0) {
          let currentName = store.get("currentName");
          if (currentName) {
            req.map((item, index) => {
              if (item.name == currentName) {
                that.setData({
                  largeclassList: req,
                  catHighLightIndex: index,
                  currentName: item.name,
                  topList: item.subCategory,
                  currentSubId: item.subCategory[0].id,
                  topIndex: 0
                });
                that.getSubList();
                store.remove("currentName");
                return false;
              } else {
                that.setData({
                  largeclassList: req,
                  subList: []
                });
              }
            });
            return false;
          }
          this.setData({
            largeclassList: req,
            subList: [],
            currentSubId: req[0].subCategory[0].id
          });
          that.getSubList();
        }
      });
    },
    catClickFn(e) {
      console.log(e);
      let dataIndex = e.currentTarget.dataset.index;
      that.setData({
        catHighLightIndex: dataIndex,
        topList: that.data.largeclassList[dataIndex].subCategory,
        topIndex: 0,
        currentSubId: that.data.largeclassList[dataIndex].subCategory[0].id,
        subList: []
      });
      wx.showLoading({
        title: "加载商品中..."
      });
      this.getSubList();
    },
    recommendClick(e) {
      console.log(e);
      let dataIndex = e.currentTarget.dataset.index;
      that.setData({
        catHighLightIndex: dataIndex,
        topList: [],
        topIndex: 0,
        subList: []
      });
      wx.showLoading({
        title: "加载商品中..."
      });
    },
    topClickFn(e) {
      let dataIndex = e.currentTarget.dataset.index;
      let subId = e.currentTarget.dataset.id;
      that.setData({
        topIndex: dataIndex,
        currentSubId: subId,
        subList: []
      });
      wx.showLoading({
        title: "加载商品中..."
      });
      this.getSubList();
    }
  }
});